package com.mediacloud.app.newsmodule.activity.audio;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chinamcloud.audioserver.APSHelper;
import com.chinamcloud.audioserver.MusicEntity;
import com.chinamcloud.audioserver.TaskAudioConfig;
import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.eventTrack.CDPTrackReportManager;
import com.eventTrack.TXReportManager;
import com.lzf.easyfloat.EasyFloat;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.assembly.widget.EmbedRecyclerView;
import com.mediacloud.app.model.adaptor.BaseAdaptor;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.Spider;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.utils.ViewUtils;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi;
import com.mediacloud.app.newsmodule.model.AudioDetailAnchorListBean;
import com.mediacloud.app.newsmodule.newsdetail_component.NewsDetailComponentUtils;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.AddPlayDurationUtils;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.GetUrlToolKt;
import com.mediacloud.app.newsmodule.utils.GridSpacingItemDecoration;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.support.SupportKit;
import com.mediacloud.app.quanzi.model.BaseDataBean;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.liteav.demo.superplayer.model.entity.AlbumDetail;
import com.tencent.liteav.demo.superplayer.model.entity.AlbumRecommend;
import com.tencent.liteav.demo.superplayer.model.entity.PublishArticlePage;
import com.utils.DeviceUtils;
import com.utils.read.AudioFloatManager;
import com.zimeiti.details.MediaAuthorDetailActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import xyz.doikki.videoplayer.util.PlayerUtils;

/**
 * 音频直播类
 *
 * @author x
 */
@SuppressWarnings("ALL")
public class AudioVodDetailActivityHalfCCTV7 extends BaseAudioActivityHalfCCTV7 {
    //码率

    private List<String> bitRateUrls = new ArrayList<>();
    private List<String> bitRateTitles = new ArrayList<String>();
    private AudioStreamLineAdaptor bitRateAdapter;

    private List<String> speedList = new ArrayList<>();
    private AudioSpeedAdaptor speedAdaptor;
    private String speed = "1.0X";

    private boolean isLoop = false;
    private int speedIndex = 3;
    private int bitRateIndex = 0;
    private NewsDetailInvoker newsDetailInvoker;//专辑列表详情或普通音频详情
    private NewsDetailInvoker itemDetailInvoker;//专辑列表中的音频的详情
    // private AudioDetailCallBack audioDetailCallBack;

    protected List<ArticleItem> audioList = new ArrayList<ArticleItem>();
    // private List<Program> programList;
    private AudioAlbumProgramWinX audioAlbumProgramWin;
    private RecyclerView recommendRecyclerView;
    private EmbedRecyclerView rvAnchor;
    private GridAudioAlbumRecommendAdapter audioAlbumRecommendAdapter;
    private AudioAnchorListAdapter audioAnchorListAdapter;
    //  private List<SeriesRecommendDto> seriesRecommendDtos;
    long mTyReportStartTime = 0;
    long mTyReportEndTime = 0;
    private Long launchTimeLong = 0L;

    private AddPlayDurationUtils addPlayDuration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPlayDuration = new AddPlayDurationUtils(getApplicationContext(), getIntent());
        speedIv.setVisibility(View.VISIBLE);
        speedIv.setOnClickListener(this);
        launchTimeLong = System.currentTimeMillis();
        setAudioPlayInfo();
        newsDetailInvoker = new NewsDetailInvoker(new AudioDetailCallBack(false));
        itemDetailInvoker = new NewsDetailInvoker(new AudioDetailCallBack(true));
        seekBack15 = findViewById(R.id.seekBack15);
        seekForward15 = findViewById(R.id.seekForward15);
        seekBack15.setEnabled(true);
        seekForward15.setEnabled(true);
        lastAudio = findViewById(R.id.lastAudio);
        nextAudio = findViewById(R.id.nextAudio);
        audioAlbumProgramAdapter = new AudioAlbumProgramAdapter();
        /*webBrowser.setWebViewClient(new WebBrowser.WebClient(this, webBrowser) {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                initWebBrowser();
            }
        });*/
        if (audioType == 2) {
            programView.setVisibility(View.VISIBLE);
            lastAudio.setVisibility(View.VISIBLE);
            nextAudio.setVisibility(View.VISIBLE);
            nextAudio.setOnClickListener(this);
            lastAudio.setOnClickListener(this);
            String articleId = getIntent().getStringExtra("articleId");
            String albumId = getIntent().getStringExtra("albumId");
            String orderDir = getIntent().getStringExtra("orderDir");

            getDirectoryList(albumId,orderDir);
            //  programList = getIntent().getParcelableArrayListExtra("PROGRAM_LIST");
            programView.setOnClickListener(this);
            summaryLayout.setVisibility(View.GONE);
            //seriesRecommendDtos = getIntent().getParcelableArrayListExtra("RECOMMEND_LIST");
            if (articleId != null) {
                getRecommendListData(articleId);

                recommendRecyclerView = findViewById(R.id.recommendRecyclerView);
                recommendRecyclerView.setVisibility(View.GONE);
                recommendRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
                GridSpacingItemDecoration decor = new GridSpacingItemDecoration(3, getResources().getDimensionPixelSize(R.dimen.dimen12), true);
                recommendRecyclerView.addItemDecoration(decor);
                audioAlbumRecommendAdapter = new GridAudioAlbumRecommendAdapter();
                recommendRecyclerView.setAdapter(audioAlbumRecommendAdapter);

                audioAlbumRecommendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        closeFlag = true;
                        AlbumRecommend rec = audioAlbumRecommendAdapter.getData().get(position);
                        ArticleItem item = new ArticleItem();
                        item.setType(TypeX.NEWS.AUDIO_COLLECTION);
                        item.setId(rec.getRelaArticleId());
                        NewsItemClickUtils.OpenItemNewsHandle(AudioVodDetailActivityHalfCCTV7.this, TypeX.NEWS.AUDIO_COLLECTION, item, catalogItem);
                        finish();
                    }
                });

                rvAnchor = findViewById(R.id.rv_audio_detail_anchor);
                rvAnchor.setLayoutManager(ViewUtils.generateRecyclerLinearLayoutManager(this, true));
                audioAnchorListAdapter = new AudioAnchorListAdapter();
                rvAnchor.setAdapter(audioAnchorListAdapter);
                initAnchorData(articleId);

                audioAnchorListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        AudioDetailAnchorListBean item = (AudioDetailAnchorListBean) adapter.getItem(position);
                        Intent intent = new Intent();
                        intent.setClassName(AudioVodDetailActivityHalfCCTV7.this, "com.mediacloud.app.newsmodule.activity.audio.AudioAnchorWorksActivity");
                        intent.putExtra("anchorId", item.getId() + "");
                        intent.putExtra("anchorName", item.getNickname() + "");
                        intent.putExtra("anchorAvatar", item.getAvatar() + "");
                        intent.putExtra("anchorPlayCount", item.getArticleHitCount() + "");
                        startActivity(intent);
                    }
                });
            }

        } else {
            programView.setVisibility(View.GONE);
//            lastAudio.setVisibility(View.GONE);
//            nextAudio.setVisibility(View.GONE);
        }
        if (audioType == 1 ){
            speedIv.setVisibility(View.GONE);
            tvMax.setText("00:00");
            seekbar.setProgress(100);

        }else{
            seekBack15.setOnClickListener(this);
            seekForward15.setOnClickListener(this);
        }


        getAudioDetail();
        //     updatePlayModeDrawable();
        onPageStart();
        AddMedalStatistics.addMedalStatistics(this);//勋章统计
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                startPos = apsKit.getCurrentPosition();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                stopTouchPos = apsKit.getCurrentPosition();
                TXReportManager.getInstance().app_jhapp_content_detail_interact(
                        (stopTouchPos >= startPos) ? "拖动音频进度条（快进）" : "拖动音频进度条（快退）",
                        null,
                        null,
                        articleItem,
                        0,
                        null,
                        null,
                        null,
                        null,
                        null,
                        null,
                        PlayerUtils.stringForTime((int) startPos),
                        PlayerUtils.stringForTime((int) stopTouchPos));
            }
        });
    }


    private void initAnchorData(String articleId) {
//        Map<String, String> map = new HashMap<>();
//        map.put("msg_user_id", UserInfo.getUserInfo(this).getMessageUserId());
        DataInvokeUtil.getZiMeiTiApi()
                .getAnchorList(articleId)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(JSONObject jsonObject) {
                        try {
                            JSONArray data = jsonObject.optJSONArray("data");
                            if (data != null) {
                                List<AudioDetailAnchorListBean> listData = FunKt.jsonToArrayList(data.toString(), AudioDetailAnchorListBean.class);
                                if (listData.size() > 0) {
                                    findViewById(R.id.tv_audio_detail_anchor).setVisibility(View.VISIBLE);
                                    rvAnchor.setVisibility(View.VISIBLE);
                                    audioAnchorListAdapter.setNewData(listData);
                                } else {
                                    findViewById(R.id.tv_audio_detail_anchor).setVisibility(View.GONE);
                                    rvAnchor.setVisibility(View.GONE);
                                }
                            } else {
                                findViewById(R.id.tv_audio_detail_anchor).setVisibility(View.GONE);
                                rvAnchor.setVisibility(View.GONE);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        findViewById(R.id.tv_audio_detail_anchor).setVisibility(View.GONE);
                        rvAnchor.setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        EasyFloat.hideAppFloat(AudioFloatManager.AUDIO_FLOAT_TAG);
    }


    @Override
    protected void onPause() {
        super.onPause();
        EasyFloat.showAppFloat(AudioFloatManager.AUDIO_FLOAT_TAG);
    }

    /**
     * 获取目录列表数据
     *
     * @param albumId
     */
    private void getDirectoryList(String albumId,String orderDir) {
        SpiderCmsApi.getSpiderCmsApi(this)
               .findPublishArticlePage(albumId, 1, 1000,orderDir,"publishDate")
                .enqueue(new Callback<PublishArticlePage>() {
                    @Override
                    public void onResponse(Call<PublishArticlePage> call, Response<PublishArticlePage> response) {
                        if (isFinishing() || isDestroyed()) {
                            return;
                        }
                        if (response.isSuccessful()) {
                            if (response.body() != null && response.body().data != null) {
                                List<AlbumDetail> data = response.body().data.pageRecords;
                                if (data != null && data.size() > 0) {
                                    audioAlbumProgramAdapter.setNewData(data);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<PublishArticlePage> call, Throwable t) {

                    }
                });
    }


    /**
     * 获取推荐列表数据
     *
     * @param articleID
     */
    private void getRecommendListData(String articleID) {
        SpiderCmsApi.getSpiderCmsApi(this).
                getSeriesRecommendByArticleId(articleID)
                .enqueue(new Callback<BaseDataBean<List<AlbumRecommend>>>() {
                    @Override
                    public void onResponse(Call<BaseDataBean<List<AlbumRecommend>>> call, Response<BaseDataBean<List<AlbumRecommend>>> response) {
                        if (isFinishing() || isDestroyed()) {
                            return;
                        }
                        if (response.isSuccessful()) {
                            if (response.body().isSuccess()) {
                                List<AlbumRecommend> data = response.body().getData();
                                if (data != null && data.size() > 0) {
                                    if (data.size() > 6) {
                                        data = data.subList(0, 6);
                                    }
                                    findViewById(R.id.recommendTitle).setVisibility(View.VISIBLE);
                                    audioAlbumRecommendAdapter.setNewData(data);
                                }
                            }
                        }

                    }

                    @Override
                    public void onFailure(Call<BaseDataBean<List<AlbumRecommend>>> call, Throwable t) {

                    }
                });
    }


    private void setAudioPlayInfo() {
        speedList.add("2.0 X");
        speedList.add("1.5 X");
        speedList.add("1.25 X");
        speedList.add("1.0 X(正常)");
        speedList.add("0.75 X");
        speedList.add("0.5 X");
        TaskAudioConfig config = APSHelper.getTaskConfig("" + articleItem.getId());
        if (config != null) {
            try {

                isLoop = config.getLoop();
                speedIndex = config.getSpeedIndex();
                bitRateIndex = config.getBitRateIndex();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        speedIv.setVisibility(View.VISIBLE);
        setSpeed();
    }


    private void setSpeed() {
        switch (speedIndex) {
            case 0:
                //  speedIv.setImageResource(R.drawable.audio_speed0);
                speedIv.setText("2.0 X");
                changeSpeed(2.0f);
                break;
            case 1:
                //speedIv.setImageResource(R.drawable.audio_speed1);
                speedIv.setText("1.5 X");
                changeSpeed(1.5f);
                break;
            case 2:
                //speedIv.setImageResource(R.drawable.audio_speed2);
                speedIv.setText("1.25 X");
                changeSpeed(1.25f);
                break;
            case 3:
                //speedIv.setImageResource(R.drawable.audio_speed3);
                speedIv.setText("倍速");
                changeSpeed(1.0f);
                break;
            case 4:
                //speedIv.setImageResource(R.drawable.audio_speed3);
                speedIv.setText("0.75 X");
                changeSpeed(0.75f);
                break;
            case 5:
                //speedIv.setImageResource(R.drawable.audio_speed3);
                speedIv.setText("0.5 X");
                changeSpeed(0.5f);
                break;
        }
    }


    @Override
    protected void onPaidAudio(String audio) {
        articleItem.setAudio(audio);
        optPlayUrl();
    }


    public void fault(Object data) {

    }

    @Override
    public void onToggleClick() {
        super.onToggleClick();
        apsKit.setLoop(isLoop);
        setSpeed();
    }

    @Override
    public void onProgramViewClick() {
        super.onProgramViewClick();

        if (audioAlbumProgramWin == null) {
            audioAlbumProgramWin = new AudioAlbumProgramWinX(this);
            audioAlbumProgramAdapter.setApsKit(apsKit);
            audioAlbumProgramWin.setAdaptor(audioAlbumProgramAdapter);
            audioAlbumProgramAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    String oldId = "";
                    String newId = "";
                    MusicEntity oldMusic = apsKit.getCurrentMusic();
                    if (oldMusic != null) {
                        oldId = oldMusic.getId();
                    }
                    try {
                        if (apsKit != null) {
                            apsKit.switchTo(position, false);
                        }
                        MusicEntity newMusic = apsKit.getCurrentMusic();
                        if (newMusic != null) {
                            newId = newMusic.getId();
                        }
                        if (!oldId.equals(newId)) {
                            audioAlbumProgramAdapter.notifyDataSetChanged();
                        }
                        audioAlbumProgramWin.dismiss();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
        }
        if (audioAlbumProgramWin.isShowing()) {
            return;
        }
        audioAlbumProgramWin.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
        audioAlbumProgramWin.setOnDismissListener(() -> {
            backgroundAlpha(1f);
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        speed = speedIv.getText().toString();
//        String fromPosition = String.valueOf(apsKit.getCurrentPosition());
        String fromPosition = PlayerUtils.stringForTime((int) apsKit.getCurrentPosition());
        if ("倍速".equals(speed)) {
            speed = "1.0X";
        }
        if (id == R.id.loopModeBtn) {
            isLoop = !isLoop;
            updatePlayModeDrawable();
            apsKit.setLoop(isLoop);
        } else if (id == R.id.speedIv) {
            showSpeedView();
        } else if (id == R.id.seekBack15) {
            TXReportManager.getInstance().app_jhapp_content_detail_interact("快退按钮",
                    null,
                    null,
                    articleItem,
                    0,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    PlayerUtils.stringForTime((int) apsKit.getCurrentPosition()));

            long seek = apsKit.getCurrentPosition() - 15 * 1000;
            if (seek < 0L) {
                seek = 0L;
            }
            apsKit.seek(seek);
        } else if (id == R.id.seekForward15) {
            TXReportManager.getInstance().app_jhapp_content_detail_interact("快进按钮",
                    null,
                    null,
                    articleItem,
                    0,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    PlayerUtils.stringForTime((int) apsKit.getCurrentPosition()));

            apsKit.seek(apsKit.getCurrentPosition() + 15 * 1000);
        } else if (id == R.id.nextAudio) {
            TXReportManager.getInstance().app_jhapp_content_detail_interact("切换下一条音频",
                    isCompleted ? "是" : "否",
                    String.valueOf((stopPosition - startPosition)/1000),
                    articleItem,
                    0,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    PlayerUtils.stringForTime((int) stopPosition));

            apsKit.stop();
            apsKit.skipToNext();
        } else if (id == R.id.lastAudio) {
            TXReportManager.getInstance().app_jhapp_content_detail_interact("切换上一条音频",
                    isCompleted ? "是" : "否",
                    String.valueOf((stopPosition - startPosition)/1000),
                    articleItem,
                    0,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    PlayerUtils.stringForTime((int) stopPosition));

            apsKit.stop();
            apsKit.skipToPrevious();
        }

    }

    /**
     * 选择倍速弹框
     */

    private void showSpeedView() {
        if (audioBottomPopWin.isShowing()) {
            return;
        }
        if (speedAdaptor == null) {
            speedAdaptor = new AudioSpeedAdaptor(this, speedList);
        }
        audioBottomPopWin.setListAdaptor(speedAdaptor);
        audioBottomPopWin.setPopTitle("倍速播放");
        audioBottomPopWin.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                speedIndex = position;
                setSpeed();
                TXReportManager.getInstance().app_jhapp_content_detail_interact("点击倍速",
                        null,
                        null,
                        articleItem,
                        0,
                        null,
                        PlayerUtils.stringForTime((int) startPosition),
                        null,
                        null,
                        speed,
                        speedIv.getText().toString());
            }
        });
        audioBottomPopWin.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.3f);
        audioBottomPopWin.setOnDismissListener(() -> {
            backgroundAlpha(1f);
        });
    }

    private void changeSpeed(float speed) {
        apsKit.setSpeed(speed);

    }


    protected void updatePlayModeDrawable() {
//        Drawable drawable = null;
//        if (isLoop) {
//            drawable = ContextCompat.getDrawable(this, R.drawable.audio_loop_open);
//        } else {
//            drawable = ContextCompat.getDrawable(this, R.drawable.audio_loop_close);
//        }
//        loopModeBtn.normalImg = loopModeBtn.pressImg = drawable;
//        loopModeBtn.updateEffDrawable();
    }


    class AudioDetailCallBack implements DataInvokeCallBack<ArticleItemReciver> {
        private boolean isItem;

        public AudioDetailCallBack(boolean isItem) {
            AudioDetailCallBack.this.isItem = isItem;
        }

        @Override
        public void success(ArticleItemReciver data) {
            if (isFinishing() || isDestroyed()) {
                return;
            }
            if (isItem) {
                setItemData(data);
            } else {
                if (data != null){
                    setDataFromNet(data.state, data.articleItem, data.components);
                    ReportKit.INSTANCE.escalationArticle(data.articleItem.getId()+"", data.articleItem.getTitle(),data.articleItem.getPublishdate(),data.articleItem.getAddUser());
                }
            }
            collectionController.articleItem = data.articleItem;

            tvMax.setText(articleItem.getProp4());
            CDPTrackReportManager.getInstance().setCurrentPageName(articleItem.getTitle());

        }

        @Override
        public void fault(Object data) {
            if (isFinishing() || isDestroyed()) {
                return;
            }
            ToastUtil.show(AudioVodDetailActivityHalfCCTV7.this, R.string.noraml_newserror);
        }
    }

    private void setItemData(ArticleItemReciver data) {
        if (data != null && data.articleItem != null) {
            ArticleItem albumDetail = data.articleItem;
            articleItem = data.articleItem;
            sendExposureEvent();
            String imgUrl = null;
            try {
                //imgUrl = (String) new JSONObject(albumDetail.getAppCustomParams()).optJSONObject("customStyle").optJSONArray("imgPath").get(0);
                if (TextUtils.isEmpty(albumDetail.getProp1())) {
                    imgUrl = albumDetail.getLogo();
                } else {
                    imgUrl = albumDetail.getProp1();
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
                       /* if (TextUtils.isEmpty(imgUrl)){
                            imgUrl=albumDetail.getImagePath();
                        }*/

            showMusicData(imgUrl, albumDetail.getTitle()
                    , albumDetail.getContent(), albumDetail.getAuthor(), albumDetail.getReferName(), getSpiderFromArticle(albumDetail));


        }
    }


    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(AudioVodDetailActivityHalfCCTV7.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0", articleItem);
            }
        });
    }

    protected void optPlayUrl() {

        try {
            String appCustomParams = articleItem.getAppCustomParams();
            JSONObject jsonObject = new JSONObject(appCustomParams);
            JSONObject movie = jsonObject.optJSONObject("movie");
            String path = movie.optString("livePath");
            String liveDomain = movie.optString("liveDomain");
            String liveId = movie.optString("liveId");
            String txFlag = movie.optString("txFlag");
            if (audioType == 1&&"1".equals(txFlag)){//直播
                String url = GetUrlToolKt.encodeUrl(liveDomain,liveId);
                MusicEntity musicEntity = new MusicEntity(articleItem.getTitle(),url);
                musicEntity.setAlbum("");
                musicEntity.setSinger("");
                apsKit.setData(musicEntity);
            }else {
                JSONObject video = new JSONObject(articleItem.getAudio());
                JSONArray tsAddress = video.optJSONArray("PC");
                cdnEncrypt = video.optString("cdnConfigEncrypt");
                bitRateTitles.clear();
                bitRateUrls.clear();
                for (int i = 0; i < tsAddress.length(); i++) {

                    JSONObject line = tsAddress.optJSONObject(i);
                    String title = line.optString("title");
                    String url = line.optString("url");
                    if (url.endsWith(".wav")) {
                        //播放器不支持wav的格式。先这样处理。后期要花时间去编译ijk的so库
                        continue;
                    }
                    bitRateUrls.add(url);
                    bitRateTitles.add(title);
                }

                if (bitRateIndex < bitRateUrls.size()) {
                    MusicEntity musicEntity = new MusicEntity(articleItem.getTitle(), bitRateUrls.get(bitRateIndex));
                    musicEntity.setAlbum("");
                    musicEntity.setSinger("");
                    apsKit.setData(musicEntity);
                    String title = bitRateTitles.get(bitRateIndex);
                    streamLineBtn.setText(title);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show(this, R.string.noraml_newserror);
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    protected List<View> getPaidViews() {
        List<View> list = new ArrayList<>();
        list.add(seekbar);
        return list;
    }

    @Override
    public void finish() {
        super.finish();
        setResult(RESULT_OK);
        articleItem.setPreview(articleItem.getTitle());
        if (addPlayDuration != null) {
            addPlayDuration.finish(articleItem);
        }
        if (apsKit.intentPlaying() || apsKit.isPlaying()) {
            if (apsKit.isTaskPlaying()) {
                TaskAudioConfig config = new TaskAudioConfig(isLoop, speedIndex, bitRateIndex);
                APSHelper.saveTaskConfig("" + articleItem.getId(), config);
            }
            if (closeFlag) {
                KillMusicUtils.hideReadNewsWin();
                realFinish();
            } else {
                sendShowFloaWinMsg();
            }
        } else {
            KillMusicUtils.hideReadNewsWin();
            realFinish();
        }

    }

    @Override
    public void realFinish() {
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis();
        }
        super.realFinish();
    }

    private void setDataFromNet(boolean state, ArticleItem articleItemData, ArrayList<ComponentItem> componentsData) {
        if (state) {
            if (articleItem != null && articleItem.getId() == articleItemData.getId()) {
                mTyReportEndTime = mTyReportStartTime = System.currentTimeMillis();
            }
            // if (articleItem != null && articleItem.getFromComponent() != 1)
            articleItem = articleItemData;
            if (audioType != 2) {
                refreshMusicData();
            }
            // tvPlayCount.setText(StringUtils.toTenThousand(articleItem.getHitCount_format()) + "播放");
           /* if (TextUtils.isEmpty(articleItem.getAuthor())) {
                tvAuthor.setVisibility(View.GONE);
            } else {
                tvAuthor.setVisibility(View.VISIBLE);
                tvAuthor.setText(articleItem.getAuthor());
            }
            tvPublishData.setText(articleItem.getPublishdate_format());
*/

            if (DeviceUtils.isCus(this) && !TextUtils.isEmpty(articleItem.getContent())) {
                tabContainer.setVisibility(View.VISIBLE);
                ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) textWeb.getLayoutParams();
                layoutParams.topMargin = floatContainer.getBottom();
                textWeb.setLayoutParams(layoutParams);
                textWeb.loadDataWithBaseURL("about:blank",
                        articleItem.getContent().replace("#appfactoryContentJS#", "").replace("#appfactoryContentJSHead#", ""),
                        "text/html", "UTF-8", null);
                soundTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isSoundMod = true;
                        textWebContainer.setVisibility(View.GONE);
                        soundTv.setTextColor(Color.WHITE);
                        textTv.setTextColor(getResources().getColor(R.color.b3ffffff));
                        soundLine.setVisibility(View.VISIBLE);
                        textLine.setVisibility(View.GONE);
                    }
                });
                textTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        isSoundMod = false;
                        textWebContainer.setVisibility(View.VISIBLE);
                        soundTv.setTextColor(getResources().getColor(R.color.b3000000));
                        textTv.setTextColor(getResources().getColor(R.color.b3000000));
                        soundLine.setVisibility(View.GONE);
                        textLine.setVisibility(View.VISIBLE);
                    }
                });
            } else {
                tabContainer.setVisibility(View.GONE);
            }
            //setLogo();
            loadedImg = false;
            refreshBottomStyle(articleItemData, 1);


            if (audioType != 2) {
                /*if (TextUtils.isEmpty(articleItem.getSummary())) {
                    setCl_lyaoutVisiable(View.GONE);
                } else {
                    // setCl_lyaoutVisiable(View.VISIBLE);
                    //老谭说这里先不要
                    setCl_lyaoutVisiable(View.GONE);
                    audioDes.setText(articleItem.getSummary());
                }*/

                optPlayUrl();
                startAddIntegralCounter();

            }

            componentLinear.removeAllViews();
            NewsDetailComponentUtils.addComponentList(componentLinear, componentsData, articleItem, AudioVodDetailActivityHalfCCTV7.this, getSupportFragmentManager(), 1);

        } else {
            ToastUtil.show(AudioVodDetailActivityHalfCCTV7.this, R.string.noraml_newserror);

        }
    }

    /**
     * 获取当前播放的音频的点赞和收藏状态
     * */
    private void checkActionStatus(boolean collected) {
        text_collect_audio.setEnabled(true);
        if (collected){
            text_collect_audio.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    R.drawable.icon_collected_audio,
                    0,
                    0
            );
        }else {
            text_collect_audio.setCompoundDrawablesWithIntrinsicBounds(
                    0,
                    R.drawable.icon_collect_audio,
                    0,
                    0
            );
        }
    }

    @Override
    public void onCollectionOk(String sourceId, boolean collected, String msg) {
        checkActionStatus(collected);
    }

    @Override
    public void onCollectionStatus(String sourceId, boolean collected) {
        checkActionStatus(collected);
    }

    @Override
    public void getLikeStatus() {
        try {
            SupportKit.INSTANCE.initSupportViewState(this,SupportKit.TYPE_1,articleItem.getId(),text_like_audio);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Spider mSpider;

    protected void getAudioDetail() {
        if (isFinish)
            return;
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        newsDetailInvoker.getArticleById(String.valueOf("" + articleItem.getId()), navigate_id, false);
    }

    private String mContent;

    private Spider getSpiderFromArticle(ArticleItem articleItem) {
        if (articleItem == null) {
            return null;
        }
        if (articleItem.getSpider() != null) {
            return articleItem.getSpider();
        }
       /* if (!TextUtils.isEmpty(articleItem.getAuthorId())&&!"0".equals(articleItem.getAuthorId())){
            Spider spider=new Spider();
            spider.setUserId(articleItem.getAuthorId());
            spider.setUserNickName(articleItem.getAuthorNickName());
            spider.setUserImage(articleItem.getAuthorAvator());
            spider.setUserName(articleItem.getAuthorNickName());
            return spider;
        }*/
        return null;

    }


    /*private void initWebBrowser() {
        webBrowser.postDelayed(new Runnable() {
            @Override
            public void run() {
                ViewGroup.LayoutParams params = webBrowser.getLayoutParams();
                if (webBrowser.getHeight() > webMaxHeight) {
                    params.height = webMaxHeight;
                    tv_webmore.setVisibility(View.VISIBLE);
                    tv_webmore.setSelected(false);
                    setWebMore();
                } else {
                    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    tv_webmore.setVisibility(View.GONE);
                }
                webBrowser.setLayoutParams(params);
                webBrowser.setVisibility(View.VISIBLE);
            }
        },100);

    }*/

    void showMusicData(String coverUrl, String title, String content
            , String author, String source, Spider spider) {
        setLogo(coverUrl);
        if (!TextUtils.isEmpty(title))
            titleView.setText(title);
        if (!TextUtils.isEmpty(content)) {
            webBrowser.setVisibility(View.VISIBLE);
            webBrowser.setIs2NewPage(true);
            webBrowser.loadData(content, "text/html", "UTF-8");
        } else {
            webBrowser.setVisibility(View.GONE);
        }

//        if (!TextUtils.isEmpty(content)) {
//            tvLayout.setVisibility(View.VISIBLE);
//            tvLayout.setContent(content);
//        } else {
//            tvLayout.setVisibility(View.GONE);
//        }

        if (!TextUtils.isEmpty(author) && !"null".equals(author)) {
            text_editor.setText("责编：" + author);
            text_editor.setVisibility(View.GONE);
        } else {
            text_editor.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(source) && !"null".equals(source)) {
            text_source.setText("来源：" + source);
            text_source.setVisibility(View.GONE);
        } else {
            text_source.setVisibility(View.GONE);
        }
        //if (!TextUtils.isEmpty(albumDetail.getAuthorId()) && !"0".equals(albumDetail.getAuthorId())) {
        if (spider != null) {
            mSpider = spider;
            articleItem.setSpider(spider);
            spiderView.setDate(articleItem);
            spiderView.setVisibility(View.GONE);
        } else {
            spiderView.setVisibility(View.GONE);
        }
    }

    @Override
    void refreshMusicData() {

        /*try {
            JSONArray imgPath1 = null;
            imgPath1 = new JSONObject(articleItem.getAppCustomParams()).optJSONObject("customStyle").optJSONArray("imgPath");
            Log.e("tag","sssssss"+articleItem.getAppCustomParams()+"---"+articleItem.getProp1());
           //String st = (String) imgPath1.get(0);
            Log.e("ta","sssssssssss id="+articleItem.getId());
            Log.e("tag","Sssssssss audioType="+audioType+"articleItem.getType="+articleItem.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        if (audioType != 2) {
            String title = articleItem.getTitle();
            if (!TextUtils.isEmpty(articleItem.getReal_title())) {
                title = articleItem.getReal_title();
            }
            String imgUrl = null;
            if (!TextUtils.isEmpty(articleItem.getProp1())){
                imgUrl = articleItem.getProp1();
            }else{
                imgUrl = articleItem.getLogo();
            }
            if (articleItem.getType() == 35) {//合集
//                try {
//                    imgUrl = (String) new JSONObject(articleItem.getAppCustomParams()).optJSONObject("customStyle").optJSONArray("imgPath").get(0);
//                } catch (Exception e) {
//                    e.printStackTrace();
//
//                }
            } else if (articleItem.getType() == 11) {//单集
//                try {
//                    imgUrl = (String) new JSONObject(articleItem.getAppCustomParams()).optJSONObject("customStyle").optJSONArray("imgPath").get(0);
//                } catch (Exception e) {
//                    e.printStackTrace();
//
//                }
                //                点播音频(type 为 11)
//                视频文稿详情页的标题也用和图文文稿一样的逻辑：
//                先取real_title,为空的情况下取title
                if (!TextUtils.isEmpty(articleItem.getReal_title())) {
                    title = articleItem.getReal_title();
                }
                /*if (!TextUtils.isEmpty(articleItem.getProp1())) {
                    imgUrl = articleItem.getProp1();
                }*/
            } else {
                try {
                  //  imgUrl = (String) new JSONObject(articleItem.getAppCustomParams()).optJSONObject("customStyle").optJSONArray("imgPath").get(0);
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }


            showMusicData(imgUrl, title
                    , articleItem.getContent(), articleItem.getAuthor(), articleItem.getReferName(), getSpiderFromArticle(articleItem));
            return;
        }
        String id = null;
        if (apsKit != null && apsKit.getCurrentMusic() != null) {
            id = apsKit.getCurrentMusic().getId();
        }

        if (id == null) {
            id = articleItem.getId() + "";
        }
        if (id != null) {
            itemDetailInvoker.getArticleById(id, null, false);
            /*SpiderCmsApi.getSpiderCmsApi(this).getAlbumArticleDetail(id).enqueue(new Callback<BaseDataBean<AlbumDetail>>() {
                @Override
                public void onResponse(Call<BaseDataBean<AlbumDetail>> call, Response<BaseDataBean<AlbumDetail>> response) {
                    if (response != null && response.body() != null
                            && response.body().getState() == 200
                            && response.body().getData() != null) {

                    }
                }

                @Override
                public void onFailure(Call<BaseDataBean<AlbumDetail>> call, Throwable t) {

                }
            });
        */
        }

    }

    @Override
    protected void showStreamLine() {
        if (audioBottomPopWin.isShowing()) {
            return;
        }
        if (bitRateAdapter == null) {
            bitRateAdapter = new AudioStreamLineAdaptor(this, bitRateTitles);
        }
        audioBottomPopWin.setListAdaptor(bitRateAdapter);
        audioBottomPopWin.setPopTitle("选择在线播放音质");
        audioBottomPopWin.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
        audioBottomPopWin.setItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                bitRateIndex = position;
                String title = bitRateTitles.get(position);
                streamLineBtn.setText(title);
                MusicEntity entity = new MusicEntity(articleItem.getTitle(), bitRateUrls.get(position));
                entity.setAlbum("");
                entity.setSinger("");
                apsKit.setData(entity);
                apsKit.resetSourceAndPlayer();
                setSpeed();
                apsKit.toggle();
            }
        });
        backgroundAlpha(0.6f);
        audioBottomPopWin.setOnDismissListener(() -> {
            backgroundAlpha(1f);
        });

    }

    /**
     * 设置添加屏幕的背景透明度(值越大,透明度越高)
     *
     * @param bgAlpha
     */


    class AudioStreamLineAdaptor extends BaseAdaptor<String> {

        public AudioStreamLineAdaptor(Context context, List<String> list) {
            super(context, list);
        }

        public AudioStreamLineAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_vod_audiosource_change_item, null);
            }
            TextView audioLineItem = Utility.findViewById(convertView, R.id.audioLineItem);
            audioLineItem.setText(getItem(position));
            ImageView imageViewCheck = Utility.findViewById(convertView, R.id.image_checked);
            if (position == bitRateIndex) {
                imageViewCheck.setImageResource(R.drawable.mous_checked);
                imageViewCheck.setVisibility(View.VISIBLE);
            } else {
                imageViewCheck.setVisibility(View.INVISIBLE);
            }
            return convertView;
        }

    }

    class AudioSpeedAdaptor extends BaseAdaptor<String> {
        int selectedColor = Color.parseColor("#D43D3D");
        int defaultColor = Color.parseColor("#222222");

        public AudioSpeedAdaptor(Context context, List<String> list) {
            super(context, list);
        }

        public AudioSpeedAdaptor(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.aappfactory_bottom_pop_item, null);
            }
            TextView title = Utility.findViewById(convertView, R.id.title);
            title.setText(getItem(position));

            if (position == speedIndex) {
                title.setTextColor(selectedColor);
            } else {
                title.setTextColor(defaultColor);
            }

            return convertView;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readEnter(info,
                    "" + articleItem.getId(), DomainUtil.getDomain(articleItem.getUrl()),
                    articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readExit(info,
                    "" + articleItem.getId(), DomainUtil.getDomain(articleItem.getUrl()),
                    articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        //20200117修复登录后页面不刷新导致无法更新付费状态的bug
        if (UserInfo.getUserInfo(this).isLogin()) {
            getAudioDetail();
        }
    }

    @Override
    public void noNetwork() {
//        mErrorView.setVisibility(View.VISIBLE);
//        emptyTipsText.setText("网络请求失败，请点击重试");
//        mErrorView.setOnClickListener(v -> {
//            if (hasNetWork)
//                getAudioDetail();
//            else showNetWorDialog();
//        });
    }

    boolean closeFlag = false;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
           // CDPTrackReportManager.getInstance().NewsContentDetailView(articleItem,(stopPosition - startPosition)/1000);
            if (!TextUtils.isEmpty(MediaAuthorDetailActivity.intentId))
                CDPTrackReportManager.getInstance().DistrictCMContentDetailView(articleItem,((System.currentTimeMillis() - inTime) / 1000));
            TXReportManager.getInstance().app_jhapp_content_detail_interact("退出播放"
                    , isCompleted ? "是" : "否"
                    , String.valueOf((stopPosition - startPosition)/1000)
                    , articleItem);
            itemDetailInvoker.destory();
            newsDetailInvoker.destory();
            togglePauseBtn.setChecked(false);
        } catch (Exception e) {

        }
    }
}